
package com.kanjian.music.activity;

import java.util.Arrays;

import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.kanjian.music.R;
import com.kanjian.music.api.ApiRequestManager;
import com.kanjian.music.constants.GenreConstants;
import com.kanjian.music.constants.IntentConstants;
import com.kanjian.music.constants.SharedPreferenceKeyConstants;
import com.kanjian.music.entity.BaseCode;
import com.kanjian.music.entity.GeneList;
import com.kanjian.music.network.HttpLoader;
import com.kanjian.music.util.SharedPreferenceUtil;

/**
 * 第一次点击音乐基因(未选择过)展示页面
 * 
 * @author xuyanjun
 */
public class BeginDNAActivity extends BaseActivity implements LoaderCallbacks<String> {

    private RelativeLayout mLayout_beginDNA;

    private RelativeLayout mLayout_chooseDNA;

    private Button mBtn_chooseDNA;

    private LinearLayout mLayout_itemContainer;

    private String mGeneStr;

    private LayoutInflater mInflater;

    private int[] mLocalGeneArray;

    private CheckBox[] mCheckBoxArray;

    private Button mBtn_submit;

    private final int LOADERID_GETGENE = 0;

    private final int LOADERID_SETGENE = 1;

    private String mSubmitGeneStr;

    @Override
    protected void onCreate(Bundle arg0) {
        setContentView(R.layout.activity_begin_dna);
        super.onCreate(arg0);
        initView();
    }

    private void initView() {
        mInflater = LayoutInflater.from(this);
        mLayout_beginDNA = (RelativeLayout) findViewById(R.id.dna_begin_layout);
        mLayout_chooseDNA = (RelativeLayout) findViewById(R.id.dna_choose_layout);
        mGeneStr = SharedPreferenceUtil.getString(SharedPreferenceKeyConstants.SPKEY_GENE, null);
        if (TextUtils.isEmpty(mGeneStr)) {
            mLayout_chooseDNA.setVisibility(View.GONE);
        } else {
            mLayout_beginDNA.setVisibility(View.GONE);
        }
        mBtn_chooseDNA = (Button) findViewById(R.id.dna_choose_btn);
        mBtn_chooseDNA.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLayout_beginDNA.setVisibility(View.GONE);
                mLayout_chooseDNA.setVisibility(View.VISIBLE);
            }
        });
        mBtn_submit = (Button) findViewById(R.id.dna_sumbit);
        mBtn_submit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                doSubmit();
            }
        });

        mLayout_itemContainer = (LinearLayout) findViewById(R.id.dna_item_container);

        loadLocalGene();

        // load remote gene
        loadRemoteGene();
    }

    public void doSubmit() {
        if (mCheckBoxArray != null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mCheckBoxArray.length; i++) {
                if (mCheckBoxArray[i].isChecked()) {
                    sb.append(mCheckBoxArray[i].getTag());
                    if (i != mCheckBoxArray.length) {
                        sb.append(",");
                    }
                }
            }
            String genStr = mSubmitGeneStr = sb.substring(0, sb.length() - 1);

            Bundle args = new Bundle();
            args.putSerializable(IntentConstants.HTTPLOADERREQUESTPARAM,
                    ApiRequestManager.getSetGenRequest(genStr));
            getSupportLoaderManager().restartLoader(LOADERID_SETGENE, args, BeginDNAActivity.this);
        }
    }

    private void loadRemoteGene() {
        Bundle args = new Bundle();
        args.putSerializable(IntentConstants.HTTPLOADERREQUESTPARAM,
                ApiRequestManager.getGeneRequest());
        getSupportLoaderManager().restartLoader(LOADERID_GETGENE, args, this);
    }

    private void getGeneFromSharedPreference() {
        // 从SharedPreferences 获取本地设置的基因
        String localGene = SharedPreferenceUtil.getString(SharedPreferenceKeyConstants.SPKEY_GENE,
                null);
        if (!TextUtils.isEmpty(localGene)) {
            try {
                String[] geneStrArray = localGene.split(",");
                if (geneStrArray != null && geneStrArray.length > 0) {
                    mLocalGeneArray = new int[geneStrArray.length];
                    for (int i = 0; i < geneStrArray.length; i++) {
                        mLocalGeneArray[i] = Integer.parseInt(geneStrArray[i]);
                    }
                }
            } catch (NumberFormatException e) {
            }
        }
    }

    private void loadLocalGene() {

        getGeneFromSharedPreference();

        // 绘制界面

        final int rowCount = 4;

        int totalSize = GenreConstants.GENELIST.size();
        mCheckBoxArray = new CheckBox[totalSize];
        int lineCount = totalSize % rowCount == 0 ? totalSize / rowCount : totalSize / rowCount + 1;
        if (mLocalGeneArray != null) {
            Arrays.sort(mLocalGeneArray);
        }
        for (int i = 0; i < lineCount; i++) {
            LinearLayout line = (LinearLayout) mInflater.inflate(R.layout.view_gene_line, null);
            for (int j = 0; j < rowCount; j++) {
                int index = i * rowCount + j;
                CheckBox cb = (CheckBox) mInflater.inflate(R.layout.view_gene_item, null);
                if (mLocalGeneArray != null
                        && Arrays.binarySearch(mLocalGeneArray,
                                GenreConstants.GENELIST.get(index).mGeneId) >= 0) {
                    cb.setChecked(true);
                }
                cb.setTag(GenreConstants.GENELIST.get(index).mGeneId);
                cb.setText(GenreConstants.GENELIST.get(index).mGeneStr);
                line.addView(cb);
                mCheckBoxArray[index] = cb;
            }
            mLayout_itemContainer.addView(line);
        }
    }

    public void refreshCheckBox() {
        getGeneFromSharedPreference();
        if (mCheckBoxArray != null && mCheckBoxArray.length > 0) {
            if (mLocalGeneArray != null) {
                Arrays.sort(mLocalGeneArray);
            }
            for (int i = 0; i < mCheckBoxArray.length; i++) {
                if (mLocalGeneArray != null
                        && Arrays.binarySearch(mLocalGeneArray,
                                GenreConstants.GENELIST.get(i).mGeneId) >= 0) {
                    mCheckBoxArray[i].setChecked(true);
                }
            }
        }
    }

    @Override
    public Loader<String> onCreateLoader(int id, Bundle args) {
        return new HttpLoader(this, args);
    }

    @Override
    public void onLoadFinished(Loader<String> loader, String data) {
        if (loader.getId() == LOADERID_SETGENE) {
            BaseCode baseCode = BaseCode.getCommonCodeFromString(data);
            if (baseCode.isOKCode()) {
                SharedPreferenceUtil.put(SharedPreferenceKeyConstants.SPKEY_GENE, mSubmitGeneStr);
            }
        } else if (loader.getId() == LOADERID_GETGENE) {
            GeneList geneList = GeneList.getGeneListFromJson(data);
            if (geneList != null && geneList.mGeneList != null) {
                String value = Arrays.toString(geneList.mGeneList).replaceAll("\\[|\\]| ", "");
                if (value != null) {
                    SharedPreferenceUtil.put(SharedPreferenceKeyConstants.SPKEY_GENE, value);
                    refreshCheckBox();
                }
            }
        }
    }

    @Override
    public void onLoaderReset(Loader<String> loader) {
    }

}
